package com.cloudkinto.controller.stock;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.product.ProductInfoService;
import com.cloudkinto.service.shop.ShopService;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.stock.StockTransferService;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import com.cloudkinto.service.stock.vo.transfer.StockTransferAddReq;
import com.cloudkinto.service.stock.vo.transfer.StockTransferDetail;
import com.cloudkinto.service.stock.vo.transfer.StockTransferPageRes;
import com.cloudkinto.service.stock.vo.transfer.StockTransferVerifyReq;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-11
 */
@RestController
@Api(tags = "库内调货模块")
@RequestMapping("/api/stockTransfer")
public class StockTransferController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(StockTransferController.class);

    @Autowired
    private StockTransferService service;
    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private StockRecordService stockRecordService;
    @Autowired
    private ShopService shopService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit(getCurrentUserId(),getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated StockTransferAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId, companyId));
    }

    @UserSessionRequired
    @PostMapping("/getCost")
    @ApiOperation(value = "获取调货花费", notes = "新增")
    public SingleResult getCost(@RequestBody @Validated StockTransferAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.getCost(req, companyId));
    }

//    @GetMapping("/updateInit/{id}")
//    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
//    public SingleResult updateInit(@PathVariable("id") Long id) {
//        return service.updateInit(id);
//    }
//
//    @PutMapping("")
//    @ApiOperation(value = "修改", notes = "修改")
//    public SingleResult update(@RequestBody @Validated Object req) {
//        Long userId = getCurrentUserId();
//        return SingleResult.success("修改成功",service.update(req,userId));
//    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @PostMapping("verify")
    @ApiOperation(value = "审核操作", notes = "确认操作")
    public SingleResult verify(@RequestBody @Validated StockTransferVerifyReq req) {
        Long userId = getCurrentUserId();
        service.verify(req, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses({@ApiResponse(code = 200,message = "",response =StockTransferDetail.class )})
    public SingleResult<StockTransferDetail> detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCurrentUserId(),getCompanyId());
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "storageId",value = "所在仓库",paramType = "query"),
            @ApiImplicitParam(name = "shopOutId",value = "转出店铺",paramType = "query"),
            @ApiImplicitParam(name = "shopInId",value = "转入店铺",paramType = "query"),
            @ApiImplicitParam(name = "type", value = "0 未审核 1已审核", paramType = "query"),
            @ApiImplicitParam(name = "current",value = "当前页",paramType = "query"),
            @ApiImplicitParam(name = "pageSize",value = "pageSize",paramType = "query")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockTransferPageRes.class)})
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();
        Long userId = getCurrentUserId();
        Map<String, String> map = new HashMap<>();
        String shopOutId = request.getParameter("shopOutId");
        String shopInId = request.getParameter("shopInId");
        String type = request.getParameter("type");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("shopOutId", shopOutId);
        map.put("shopInId", shopInId);
        map.put("type", type);
        map.put("storageId", storageId);
        map.put("companyId", companyId + "");
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map, userId);
    }

    @UserSessionRequired
    @GetMapping("/stockRecordListPage")
    @ApiOperation(value = "仓库商品查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "shopId", value = "商店id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> stockRecordListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");

        map.put("keyword", keyword);
        map.put("storageId", storageId);
        map.put("inStock", "2");
        map.put("shopId", shopId);
        map.put("companyId", companyId + "");
        map.put("current", current);
        map.put("pageSize", size);
        if(StringUtils.isBlank(shopId)){
            throw new BizException(SysConstant.Pls_Chose_Out_Shop);
//            List<Map> mapList = shopService.selectShopListInit(getCurrentUserId(), getCompanyId());
//            map.put("shopId",mapList.stream().map(map1 -> String.valueOf(map1.get("id"))).collect(Collectors.joining(",")));
        }
        return stockRecordService.getListPage(map);
    }



    @UserSessionRequired
    @GetMapping("/stockRecordList")
    @ApiOperation(value = "店铺全转移库存", notes = "店铺全转移库存")
    @ApiImplicitParams({@ApiImplicitParam(name = "shopId", value = "商店id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public SingleResult stockRecordList(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        map.put("storageId", storageId);
        map.put("inStock", "2");
        map.put("shopId", shopId);
        map.put("companyId", companyId + "");
        if(StringUtils.isBlank(shopId)){
            throw new BizException(SysConstant.Pls_Chose_Out_Shop);
//            List<Map> mapList = shopService.selectShopListInit(getCurrentUserId(), getCompanyId());
//            map.put("shopId",mapList.stream().map(map1 -> String.valueOf(map1.get("id"))).collect(Collectors.joining(",")));
        }
        return SingleResult.success(stockRecordService.getList(map));
    }

}

